package com.baomidou.ant.controller;

import com.baomidou.ant.common.Result;
import com.baomidou.ant.entity.SysDept;
import com.baomidou.ant.entity.SysUser;
import com.baomidou.ant.service.ISysDeptService;
import com.baomidou.ant.service.ISysUserService;
import com.baomidou.ant.utils.MyStringUtil;
import com.baomidou.ant.utils.VoUtilsTool;
import com.baomidou.ant.vo.request.*;
import com.baomidou.ant.vo.response.ResponseEditUserInfoVo;
import com.baomidou.ant.vo.response.ResponseListUserVo;
import com.baomidou.ant.vo.response.ResponseUserInfoVo;
import com.baomidou.ant.vo.response.ResponseUserListVo;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author jobob
 * @since 2022-03-18
 */
@RestController
@RequestMapping("/sys-user")
public class SysUserController {
    @Autowired
    public ISysUserService userService;
    @Autowired
    public ISysDeptService deptService;


    //登录接口
    @PostMapping("/login")
    public Result login(HttpServletRequest request, @RequestBody LoginRequestVo loginRequestVo) {
        //获取session
        //HttpSession session = request.getSession();
        //String captcha = (String) redisTemplate.opsForValue().get(Constants.KAPTCHA_SESSION_KEY);
//        String trueCaptcha = (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
//        if (!trueCaptcha.equalsIgnoreCase(loginRequestVo.getCaptcha())) {
//            return Result.getFailure().setMsg("验证码错误");
//        }
        if(ObjectUtils.isEmpty(loginRequestVo.getLoginName())){
            return Result.getFailure().setMsg("请填写登录名");
        }
        //查询用户是否正确
        SysUser user = userService.queryByLoginName(loginRequestVo.getLoginName());
        //
        //用户不存在，loginName判断
        if (ObjectUtils.isEmpty(user)) {
            return Result.getFailure().setMsg("用户不存在");
        }
        //用户是否被禁
        if (!user.isStatus()) {
            return Result.getFailure().setMsg("用户被禁用,禁止登录");
        }
        //密码错误
        if (!Objects.equals(loginRequestVo.getPassword(),user.getPassword())) {
            return Result.getFailure().setMsg("密码错误");
        }
        //用户存在且密码正确
        Map<String,Object> result=new HashMap<>();
        result.put("userId",user.getId());
        result.put("loginName",user.getLoginName());
        return Result.getSuccess().setData(result);
    }

    //新增用户接口
    @PostMapping("/add")
    public Result register(@RequestBody RequestRegisterVo requestRegisterVo){
        //判断创建者权限
        SysUser createUser=userService.getById(requestRegisterVo.getCreateUserId());
        if(!Objects.equals(createUser.getType(), "1")){
            return Result.getFailure().setMsg("您无权添加用户,请联系超级管理员");
        }
        //信息为空
        if (VoUtilsTool.checkObjFieldIsNull(requestRegisterVo)){
            return Result.getFailure().setMsg("缺少信息");
        }
        //用户已经存在
        SysUser user=userService.queryByLoginName(requestRegisterVo.getLoginName());
        if(ObjectUtils.isNotEmpty(user)){
            return Result.getFailure().setMsg("用户已经存在");
        }
        //保存成功
        userService.addUser(requestRegisterVo);
        return Result.getSuccess().setMsg("添加成功");
    }

    //删除用户接口
    @PostMapping("/delete")
    public Result delete(@RequestBody RequestDeleteVo vo){
        SysUser user=userService.getById(vo.getUserId());
        //如果不是管理员
        if (!Objects.equals(user.getType(), "1")){
            return Result.getFailure().setMsg("您不是超级管理员，无权删除用户");
        }
        //如果是管理员
        if(userService.removeById(vo.getGoalId())){
            return Result.getSuccess().setMsg("删除成功");
        }else{
            return Result.getFailure().setMsg("删除失败");
        }
    }

    //根据id获取用户信息
    @GetMapping("/getUserInfoById/{userId}")
    public Result getUserInfoById(@PathVariable Integer userId){
        SysUser user=userService.getById(userId);
        ResponseUserInfoVo vo=new ResponseUserInfoVo();
        //属性拷贝
        vo.setUserName(user.getUserName());
        vo.setDeptName(deptService.getById(user.getDeptId()).getDept());
        vo.setType(user.getType());
        vo.setLoginName(user.getLoginName());
        if(ObjectUtils.isNotNull(user)){
            return Result.getSuccess().setData(vo);
        }else {
            return Result.getFailure().setMsg("用户不存在");
        }
    }

    //展示用户接口,条件查询
    @PostMapping("/listUser")
    public Result listUser(@RequestBody RequestUserListVo requestUserListVo){
        IPage<ResponseUserListVo> iPage=userService.userList(requestUserListVo);
        return Result.getSuccess().setData(iPage);
    }

    //超管权限判断
    @GetMapping("/getAdmin/{userId}")
    public Result getAdmin(@PathVariable Integer userId){
        SysUser sysUser=userService.getById(userId);
        //超级管理员
        if(Objects.equals(sysUser.getType(), "1")){
            return Result.getSuccess();
        }
        else{
            SysDept sysDept=deptService.getById(sysUser.getDeptId());
            return Result.getFailure().setData(sysDept);
        }
    }

    //初级权限判定
    @GetMapping("/getAdminLevel/{userId}")
    public Result getAdminLevel(@PathVariable Integer userId){
        SysUser sysUser=userService.getById(userId);
        //管理员
        if(Objects.equals(sysUser.getType(), "1")||Objects.equals(sysUser.getType(), "0")){
            return Result.getSuccess();
        }
        else{
            return Result.getFailure();
        }
    }

    //部门用户下拉框
    @PostMapping("/userList")
    public Result userList(@RequestBody RequestDtoVo requestDtoVo){
        List<ResponseListUserVo> list=userService.queryByDept(requestDtoVo.getDeptId());
        return Result.getSuccess().setData(list);
    }

    //授权接口
    @PostMapping("/addAdmin")
    public Result addAdmin(@RequestBody RequestAddAdminVo vo){
        SysUser goalUser=userService.getById(vo.getGoalId());
        if(Objects.equals(goalUser.getType(), "1")){
            return Result.getFailure().setMsg("行为禁止!");
        }
        goalUser.setType(vo.getType());
        if(userService.updateById(goalUser)){
            return Result.getSuccess().setMsg("授权成功");
        }else
            return Result.getFailure().setMsg("授权失败");
    }

    //编辑界面数据回显
    @GetMapping("/getUserInfoOfEdit/{userId}")
    public Result getUserInfoOfEdit(@PathVariable Integer userId){
        SysUser user=userService.getById(userId);
        ResponseEditUserInfoVo vo=new ResponseEditUserInfoVo();
        vo.setDeptName(deptService.getById(user.getDeptId()).getDept());
        vo.setLoginName(user.getLoginName());
        vo.setPassword(user.getPassword());
        vo.setUserName(user.getUserName());
        vo.setStatus(user.isStatus());
        int[] ids= MyStringUtil.toInt(user.getWorkScope());
        vo.setWorkScopes(ids);
        if(ObjectUtils.isNotNull(user)){
            return Result.getSuccess().setData(vo);
        }else {
            return Result.getFailure().setMsg("用户不存在");
        }
    }

    //修改信息接口
    @PostMapping("/update")
    public Result update(@RequestBody RequestUpdateUserVo requestUpdateUserVo){
        SysUser user=userService.getById(requestUpdateUserVo.getUserId());
        String oldLoginName=user.getLoginName();
        RequestChangeReCheckVo vo=new RequestChangeReCheckVo();
        //如果改了部门
        if(!Objects.equals(user.getDeptId(), requestUpdateUserVo.getDeptId())){
            user.setDeptId(requestUpdateUserVo.getDeptId());
        }
        //如果改了登录名
        if(!Objects.equals(user.getLoginName(), requestUpdateUserVo.getLoginName())){
            //记录这次改变
            vo.setOldLoginName(user.getLoginName());
            vo.setNewLoginName(requestUpdateUserVo.getLoginName());
            //更新用户数据
            user.setLoginName(requestUpdateUserVo.getLoginName());
        }
        //如果改了用户名
        if(!Objects.equals(user.getUserName(), requestUpdateUserVo.getUserName())){
            //记录这次改变
            vo.setOldUserName(user.getUserName());
            vo.setNewUserName(requestUpdateUserVo.getUserName());
            //更新用户数据
            user.setUserName(requestUpdateUserVo.getUserName());
        }
        user.setStatus(Objects.equals(requestUpdateUserVo.getStatus(), "on"));
        if(ObjectUtils.isEmpty(requestUpdateUserVo.getWorkScope())){
            user.setWorkScope("0");
        } else
            user.setWorkScope(requestUpdateUserVo.getWorkScope());
        if(userService.updateById(user)){
            //执行触发器,前提是不为空vo,即代表工号和用户名都被更改过
            if(!VoUtilsTool.isObjectNull(vo)){
                vo.setOldLoginName(oldLoginName);//作为查询唯一性条件，需要带入vo,充当查询条件;判空之后加入，是为了防止做没必要的数据库操作
                userService.changeReCheck(vo);
            }
            return Result.getSuccess().setMsg("修改成功");
        }else
            return Result.getFailure().setMsg("修改失败");
    }


    //修改信息接口
    @PostMapping("/changePsw")
    public Result changePassWord(@RequestBody RequestChangePswVo requestChangePswVo){
        SysUser user=userService.getById(requestChangePswVo.getUserId());
        user.setPassword(requestChangePswVo.getNewPsw());
        if(userService.updateById(user)){
            return Result.getSuccess().setMsg("修改成功");
        }else
            return Result.getFailure().setMsg("修改失败");
    }

}
